package com.augrain.microframework.lock;

import com.augrain.microframework.core.spring.SpringUtils;
import com.augrain.microframework.core.util.StringUtils;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.ConfigurableEnvironment;

/**
 * 当系统已经配置了redis相关配置，可以在不配置dlock的情况下，沿用redis的配置
 *
 * @author biaoy
 * @since 2020/12/16
 */
@Configuration
public class DLockSimpleConfigPreSetter implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {

    public static RedisProperties getPrimaryRedisProperties(ConfigurableEnvironment environment) {
        BindResult<RedisProperties> bind = Binder.get(environment).bind("spring.data.redis", RedisProperties.class);
        if (!bind.isBound()) {
            return null;
        }
        return bind.get();
    }

    /**
     * 提前设置一些DLock的配置，防止DLock没有配置导致的锁错误
     */
    @Override
    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent applicationEnvironmentPreparedEvent) {
        ConfigurableEnvironment environment = applicationEnvironmentPreparedEvent.getEnvironment();
        RedisProperties redisProperties = getPrimaryRedisProperties(environment);
        if (redisProperties == null) {
            return;
        }

        SpringUtils.addProperty("spring.mf.lock.address", redisProperties.getHost() + ":" + redisProperties.getPort());
        if (!StringUtils.isEmpty(redisProperties.getPassword())) {
            SpringUtils.addProperty("spring.mf.lock.password", redisProperties.getPassword());
        }
        SpringUtils.addProperty("spring.mf.lock.database", String.valueOf(redisProperties.getDatabase()));
    }
}
